import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;
import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class TcpEchoServer {
    private ServerSocket serverSocket = null;
    public TcpEchoServer(int port) throws IOException {
        serverSocket = new ServerSocket(port);
    }
    public void start() throws IOException{
        System.out.println("服务器启动");
        //使用线程池
        ExecutorService pool = Executors.newCachedThreadPool();
        while(true) {
            Socket clientSocket = serverSocket.accept();
            pool.submit(new Runnable() {
                @Override
                public void run() {
                    try{
                        processConnection(clientSocket);
                    }catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            });
        }
    }
    public void processConnection(Socket clientSocket) throws IOException{
        //1.打印日志，告诉客户端已连接
        System.out.printf("[%s %d] 客户端上线",clientSocket.getInetAddress(),clientSocket.getPort());
        //2.从socket中获取到流对象
        try(InputStream inputStream = clientSocket.getInputStream();
            OutputStream outputStream = clientSocket.getOutputStream()){
            //3.针对每个链接，客户端发来多个请求，服务器返回多个相应
            Scanner scanner = new Scanner(System.in);
            while (true) {
                //3.1读取请求并解析
                if(!scanner.hasNext()) {
                    //发现后续没有数据，说明TCP断开
                    System.out.printf("[%s %d] 客户端下线",clientSocket.getInetAddress(),clientSocket.getPort());
                    break;
                }
                String request = scanner.next();
                //3.2根据请求计算响应
                String response = process(request);
                //3.3把相应写回客户端
                outputStream.write(response.getBytes(),0,response.getBytes().length);
                //3.4打印服务器日志
                System.out.printf("[%s %d] req=%s res=%s\n",clientSocket.getInetAddress(),
                        clientSocket.getPort(),request,response);
            }
        }catch (IOException e) {
            e.printStackTrace();
        } finally {
            //关闭服务器
            clientSocket.close();
        }
    }
    private String process(String request) {
        return  request + "\n";
    }

    public static void main(String[] args) throws IOException{
        TcpEchoServer server = new TcpEchoServer(9090);
        server.start();
    }
}
